// 引入接口文件
import { queryAllAddress, getCityEstateList, getGiftDetail, houseListGet, addGift,editGift } from './giftAddServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge, get, pick } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import { makeAddress } from "utils/util"
import AppBus from 'utils/bus'

// 初始默认状态
const defultState = {
	loading: false,
	btnLoading: false,
	isShelfStatus: true,
	actionType: '',
	detail: {
		shelfStatus: true,
		isSelfTemplate: false,
		isPublishHouse:true,
		bottomImg: 'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/gift_bg_01.png',
		bottomImg2: 'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/gift_bg_01.png',
		bottomImgId:`gift-0`,
		bottomImgId2:`gift-0`,
		startOnlineTime:moment().format('YYYY-MM-DD 00:00:01'),
		endOnlineTime:moment().add(1,"months").format('YYYY-MM-DD 23:59:59'),
		startOfflineTime:moment().format('YYYY-MM-DD 00:00:01'),
		endOfflineTime:moment().add(1,"months").format('YYYY-MM-DD 23:59:59'),
		
	},
	imgModal:{
		visible:false,
		srcs:[],
	  },
	areaList: [],//省市区列表
	estateList: [],//市对应的楼盘项目
	gif: [
		'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/gift_bg_01.png',
		'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/gift_bg_02.png',
		'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/gift_bg_03.png',
		'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/gift_bg_04.png',
		'https://zmzj-pro.oss-cn-shenzhen.aliyuncs.com/admin/images/gift_bg_05.png',
	],
	isSubmit:true,
}

// 声明module
const tmpModule = {
	namespace: 'couponAddModel',
	// 默认状态
	state: cloneDeep(defultState),
	// 入口函数(先执行)
	subscriptions: {
		setup({ dispatch, history }) {
			history.listen((location) => {
				let { pathname, query } = location;
				console.log(location)
				// 页面路由匹配时执行
				if ('' + tmpModule.pathname === '' + pathname) {
					dispatch({ type: 'updateStore', payload: cloneDeep(defultState) })
					dispatch({ type: 'updateStore', payload: { actionType: query.actionType } })
					dispatch({ type: 'getAreaList', payload: {} });
					dispatch({ type: 'getCityEstateList', payload: { params: { province: '', city: '' } } })
					if (!!get(query, 'giftId', '')) {
						dispatch({ type: 'app/setTabTitle', payload: { title: '编辑礼品', location } });
						dispatch({ type: 'getDetail', payload: {  id: query.giftId } })
					} else {
						dispatch({ type: 'app/setTabTitle', payload: { title: '新增礼品', location } });
					}
				}
			})
		},
	},

	// 方法列表
	effects: {
		// 查询记录
		*getDetail({ payload }, { put, call, select }) {
			// console.log(payload)
			try {
				let { detail } = yield select(state => state[tmpModule.namespace])
				const { data, success, msg } = yield call(getGiftDetail, payload.id)
				// if (success) {
					yield put({ type: 'updateStore', payload: { detail: data } })
					// yield put({ type: 'updateStore', payload: { detail: Object.assign({}, detail, data) } })
				// }
			} catch (e) {
				console.error(e)
			}
		},

		*getAreaList({ payload }, { put, call, select }) {
			try {
				const { success, data } = yield call(queryAllAddress, {})
				if (success) {
					//todo: 接口格式调整后删除
					let areaList = []
					let arr = [data[0]]
					let attr = [data[data.length - 1]]
					data[0] = {
						label: "北京",
						value: "110100",
						children: arr
					}
					data[data.length - 1] = {
						label: "澳门",
						value: "820000",
						children: attr
					}
					//console.log(data,"data")
					//去掉第三级，
					areaList = makeAddress(data, 2, false)
					yield put({ type: 'updateStore', payload: { areaList } })
				}
			} catch (e) {
			}
		},
		// 获取户型项目
		*getHouseArea({ payload }, { put, call, select }) {
			let params = cloneDeep(payload)
			params.pageNo = 1
			params.pageSize = 999999
			try {
				const { success, rows } = yield call(houseListGet, params)
				if (success) {
					yield put({ type: 'updateStore', payload: { estateList: rows || [] } })
				}
			} catch (e) {
				console.log(e)
			}
		},
		*getCityEstateList({ payload }, { put, call, select }) {
			try {
				const data = yield call(getCityEstateList, { pageNo: 1, pageSize: 1000, ...payload.params })
				if (data.success) {
					let estateList = data.rows
					estateList && estateList.forEach((e, i) => { e.label = e.name; e.value = e.productId })
					yield put({ type: 'updateStore', payload: { estateList } });
				}
			} catch (e) {
			}
		},
		//提交表单
		*submit({ payload }, { put, call, select }) {
			try {
				yield put({ type: 'updateStore', payload: { btnLoading: true } })
				let { detail, actionType } = yield select((state) => state[tmpModule.namespace])
				
				if(detail.isSelfTemplate){
					delete detail.bottomImgId
					delete detail.bottomImg2
					delete detail.bottomImgId2
					detail.selfTemplateImg&&delete detail.selfTemplateImg
				  }

				const server = actionType == 'add'?addGift:editGift
				if(detail.projectId&&detail.projectId!=""){
					// console.log(detail)
					const { success } = yield call(server, { ...detail });

					if (success) {
						message.success(actionType=='add'?'新增成功':'编辑成功')
						hashHistory.push('/home/infoAdmin/giftList')
					}
					//   yield call(delay, 2000);
					
				}else{
					message.error('所属项目不能为空！')
					// return false
				}
				yield put({ type: 'updateStore', payload: { btnLoading: false } })
				
			} catch (e) {
				console.log(e)
			}

		},
		* dealEditor({ payload }, { put, select }) {
			let { detail } = yield select(state => state[tmpModule.namespace])
			console.log(detail)
			let newDetail=Object.assign({}, detail)
			newDetail.detail=payload.detail
			yield put({ type: 'updateStore', payload: { detail: newDetail } });
		  },

	},

	// 存入状态机
	reducers: {
		updateStore(preState, action) {
			return Object.assign({}, preState, action.payload)
		},
	}
}

export default tmpModule
